package cn.itcast.realm;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.List;


public class SaaSRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //通知shiro框架,当前登录人的菜单权限
        System.out.println("+++++进入了授权方法AuthorizationInfo");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        User user = (User) principalCollection.getPrimaryPrincipal();

        //查询用户的菜单权限
        List<Module> moduleList = moduleService.findModuleListByUser(user);

        for (Module module : moduleList) {
            authorizationInfo.addStringPermission(module.getName());
        }

        return authorizationInfo;
    }

    @Override
    //认证,在方法中完成email和password的校验
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //告诉shiro框架 当前登录人有哪些菜单权限
        System.out.println("+++++AuthenticationInfo");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String email = token.getUsername();
        String password_page = new String(token.getPassword());

        //通过email查询用户
        User user = userService.findByEmail(email);

        //判断用户是否存在
        if (user != null) {
            String password_db = user.getPassword();

            if (password_db.equals(password_page)) {
                //Object principal, Object credentials 密码, String realmName 当前realm的类名
                return new SimpleAuthenticationInfo(user, password_db, getName());
            }
        }
        return null;
    }
}
